<script>
import { atLeast } from '@/utils/kris_utils'
import { createRoom } from '@/api/dorm'
import { getDormitory } from '@/api/basic'

import RoomForm from '../RoomForm/RoomForm.vue'
import DialogContent from "@/components/DialogContent/index.vue"
export default {
  components: {
    RoomForm,
    DialogContent
  },
  props: {
    value: {
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      apartments: [],
      form: {
        apartmentID: null,
        roomName: '',
        bad: 1,
        rent: 0,
        remark:'',
        photos: []
      },
      isSubmitting: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(visible) {
        this.$emit('input', visible)
      }
    },
    isActionDisabled() {
      return this.isSubmitting
    },
    apartmentOptions() {
      return this.apartments.map(apartment => {
        const { address, id } = apartment
        return {
          label: address,
          value: id
        }
      })
    }
  },
  created() {
    console.log(this.form,'form');
    this.initData()
  },
  methods: {
    sleep(t) {
      return new Promise(r => setTimeout(r, t))
    },
    handleClose() {
      if (this.isActionDisabled) return
      this.dialogVisible = false
    },
    async getApartments() {
      // debugger
      const result = await getDormitory()
      this.apartments = result?.data ?? []
    },
    async handleConfirm() {
      try {
        const flag = await this.$refs.form?.validate()
        if (!flag) return

        this.isSubmitting = true
        await this.sleep(300)

        const params = this.buildParams()
        const result = await createRoom(params)

        if (result.code !== 201) { throw new Error(result?.data?.message ?? '添加失败') }

        this.isSubmitting = false
        this.$emit('success', result)
        this.$refs.form?.resetFields()
      } catch (e) {
        this.isSubmitting = false
        this.$emit('failed', e)
      }
    },
    buildParams() {
      const {
        apartmentID,
        roomName,
        bad,
        rent,
        photos,
        remark
      } = this.form
      console.log(this.form,'form');

      const params = {
        dormitory_id: apartmentID,
        name: roomName,
        number: bad,
        rent,
        remark:remark,
        photo: JSON.stringify(photos)
      }

      return params
    },
    async loadData() {
      const result = await Promise.allSettled([
        this.getApartments()
      ])

      const failTasks = result.filter(item => item.status === 'rejected')
      if (failTasks.length <= 0) return
      throw failTasks.at(0)
    },
    async initData() {
      try {
        await this.loadData()
      } catch (e) {

      }
    }
  }
}
</script>

<template>
  <div class="create-room">
    <DialogContent title="添加房间" :visible.sync="dialogVisible" width="30%" 
    :close-on-click-modal="false" :before-close="handleClose">
    <RoomForm ref="form" v-model="form" :apartment-options="apartmentOptions" :fetch-apartments="getApartments" />
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="isSubmitting" @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="isSubmitting" :disabled="isSubmitting" @click="handleConfirm">确 定</el-button>
      </div>
    </DialogContent>
  </div>
</template>

<style lang="scss"></style>
